﻿using Mengsk.ProxyDelivery.Domain;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Mengsk.ProxyDelivery.Print.Domain
{
    public class FilePrintTemplateRepertory
    {
        private static readonly string DATA_DIR = new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName + @"\Data\PrintTemplate";

        static FilePrintTemplateRepertory()
        {
            System.IO.Directory.CreateDirectory(DATA_DIR);
        }

        public PrintTemplate[] GetAll()
        {
            List<PrintTemplate> templates = new List<PrintTemplate>();
            foreach (string file in Directory.GetFiles(DATA_DIR, "*.pt"))
            {
                using (Stream s = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    var template = bf.Deserialize(s) as PrintTemplate;
                    templates.Add(template);
                }
            }
            return templates.ToArray();
        }

        public void Insert(PrintTemplate deliveryTemplate)
        {
            string file = System.IO.Path.Combine(DATA_DIR, deliveryTemplate.Name + ".pt");
            using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(stream, deliveryTemplate);
            }
        }

        public void Update(PrintTemplate deliveryTemplate, string newName)
        {
            if (deliveryTemplate.Name.Equals(newName) == false)
            {
                var files = Directory.GetFiles(DATA_DIR, newName + ".pt");
                if (files.Count() > 0)
                {
                    throw new Exception("已有相同模板名称存在");
                }
            }
            this.Delete(deliveryTemplate.Name);
            deliveryTemplate.Name = newName;
            this.Insert(deliveryTemplate);
        }

        public void Delete(string name)
        {
            var files = Directory.GetFiles(DATA_DIR, name + ".pt");
            if (files.Length > 0)
            {
                File.Delete(files[0]);
            }
        }
    }
}
